package com.ynunicom.midplatform.common.config;

import com.alibaba.fastjson.JSON;
import com.ynunicom.midplatform.common.exception.AsyncException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;

/**
 * 异步 配置类
 *
 * @author duwei
 * @version 2018-05-08 14:30
 */
@Configuration
@EnableAsync
@Slf4j
public class AsyncConfiguration implements AsyncConfigurer {

    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(10);
        executor.setMaxPoolSize(100);
        executor.setQueueCapacity(100);
        executor.setThreadNamePrefix("AsyncExecutorThread-");
        //如果不初始化，导致找到不到执行器
        executor.initialize();
        return executor;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return (e, method, params) -> {
            log.info("Async method: {} has uncaught exception,params:{}", method.getName(), JSON.toJSONString(params));

            if (e instanceof AsyncException) {
                AsyncException asyncException = (AsyncException) e;
                log.info("AsyncException:{}", asyncException.getErrorMessage());
            }
            e.printStackTrace();
        };
    }
}